/**
 * Copyright (c) 2010 Pablo Muñoz Galindo
 * <p>
 * Este software está licenciado bajo los términos de la licencia GNU GPLv3
 * <br>
 * Para más información:
 * <a href="http://www.gnu.org/licenses/gpl-3.0-standalone.html"> http://www.gnu.org/licenses/gpl-3.0-standalone.html </a>
 * <br>
 * Este software es distribuido "como es", no ofreciendo garantías de ningún tipo. La responsabilidad
 * de su uso queda bajo la cuenta y riesgo del propio usuario.
 *
 */
package esteganografo.gui;

import javax.swing.JFileChooser;
import org.jdesktop.application.Action;
import java.io.File;
import esteganografo.core.DecoderConAES;
import esteganografo.core.Utilities;
import javax.swing.SwingWorker;
import java.util.List;
import javax.swing.JOptionPane;
import org.bouncycastle.crypto.CryptoException;

/**
 * Cuadro de diálogo de Swing para implementar un interface para decodificar y desencriptar
 * texto encriptado en AES-128 dentro de un fichero
 *
 * @author Pablo Muñoz Galindo
 * @version 0.1b
 */
public class DecodificarTextoAESBox extends javax.swing.JDialog {

    /** Creates new form CodificarTextoEnClaroBox */
    public DecodificarTextoAESBox(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        jPasswordField2.setText("");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jProgressBar1 = new javax.swing.JProgressBar();
        jTextField2 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel6 = new javax.swing.JLabel();
        jPasswordField2 = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N
        setResizable(false);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(esteganografo.gui.EsteganografoGUIApp.class).getContext().getActionMap(DecodificarTextoAESBox.class, this);
        jButton1.setAction(actionMap.get("codificar")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(esteganografo.gui.EsteganografoGUIApp.class).getContext().getResourceMap(DecodificarTextoAESBox.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setEnabled(false);
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("cancelar")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jTextField1.setEditable(false);
        jTextField1.setText(resourceMap.getString("jFichero_Origen.text")); // NOI18N
        jTextField1.setAction(actionMap.get("examinar_fichero_orig")); // NOI18N
        jTextField1.setName("jFichero_Origen"); // NOI18N

        jButton3.setAction(actionMap.get("examinar_fichero_orig")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextPane1.setBackground(resourceMap.getColor("jTextPane1.background")); // NOI18N
        jTextPane1.setEditable(false);
        jTextPane1.setAutoscrolls(true);
        jTextPane1.setName("jTextPane1"); // NOI18N
        jTextPane1.setOpaque(false);
        jTextPane1.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                jTextPane1InputMethodTextChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jTextPane1);

        jProgressBar1.setName("jProgressBar1"); // NOI18N

        jTextField2.setEditable(false);
        jTextField2.setAction(actionMap.get("examinar_fichero_md5")); // NOI18N
        jTextField2.setEnabled(false);
        jTextField2.setName("jTextField2"); // NOI18N

        jButton4.setAction(actionMap.get("examinar_fichero_md5")); // NOI18N
        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setEnabled(false);
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jCheckBox1.setText(resourceMap.getString("jCheckBox1.text")); // NOI18N
        jCheckBox1.setActionCommand(resourceMap.getString("jCheckBox1.actionCommand")); // NOI18N
        jCheckBox1.setName("jCheckBox1"); // NOI18N
        jCheckBox1.setOpaque(true);
        jCheckBox1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jCheckBox1MouseClicked(evt);
            }
        });

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jPasswordField2.setText(resourceMap.getString("jPasswordField2.text")); // NOI18N
        jPasswordField2.setName("jPasswordField2"); // NOI18N
        jPasswordField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField2KeyTyped(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                        .addGap(84, 84, 84))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE)
                                .addComponent(jButton4))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton3))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel3))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jCheckBox1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addGap(18, 18, 18)
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextPane1InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTextPane1InputMethodTextChanged
        jLabel3.setText("Caracteres portados: " + jTextPane1.getText().length());
    }//GEN-LAST:event_jTextPane1InputMethodTextChanged

    private void jCheckBox1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jCheckBox1MouseClicked
        if (jCheckBox1.isSelected()) {
            jTextField2.setEnabled(true);
            jButton4.setEnabled(true);
        } else {
            jTextField2.setEnabled(false);
            jButton4.setEnabled(false);
        }
        isReady();

    }//GEN-LAST:event_jCheckBox1MouseClicked

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        isReady();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        isReady();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jPasswordField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField2KeyTyped
        isReady();
    }//GEN-LAST:event_jPasswordField2KeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DecodificarTextoAESBox dialog = new DecodificarTextoAESBox(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void codificar() {
        DecoderConAES decAES = new DecoderConAES(jTextField1.getText());
        try {
            dw = new DecodificadorWorker(decAES, new String(jPasswordField2.getPassword()),
                    jTextPane1, jProgressBar1, jLabel3, jCheckBox1.isSelected());
            dw.execute();
        } catch (Exception e1) {
        }
    }

    @Action
    public void cancelar() {
        dispose();
    }

    @Action
    public void examinar_fichero_orig() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(Utilities.getFiltroExtensionWAV());
        fileChooser.addChoosableFileFilter(Utilities.getFiltroExtensionBMP());
        int resultado = fileChooser.showOpenDialog(null);
        if (resultado == JFileChooser.APPROVE_OPTION) {
            File fichero = fileChooser.getSelectedFile();
            jTextField1.setText(fichero.getAbsolutePath());
        }
    }

    @Action
    public void examinar_fichero_md5() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setFileFilter(Utilities.getFiltroExtensionMD5());
        int resultado = fileChooser.showOpenDialog(null);
        if (resultado == JFileChooser.APPROVE_OPTION) {
            File fichero = fileChooser.getSelectedFile();
            jTextField2.setText(fichero.getAbsolutePath());
        }
    }

    private void isReady() {
        if (jTextField1.getText().length() > 0 & (jTextField2.getText().length() > 0 || !jCheckBox1.isSelected()) & jPasswordField2.getPassword().length > 0) {
            if (!jButton1.isEnabled()) {
                jButton1.setEnabled(true);
            }
        } else {
            if (jButton1.isEnabled()) {
                jButton1.setEnabled(false);
            }
        }
    }
    private DecodificadorWorker dw;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

    /**
     * Clase interna que extiende a SwingWorker para la tarea de decodificación del texto.
     *
     * Mediante su uso se consigue no ralentizar el entorno de usuario mientras se realizan
     * las operacines.
     */
    class DecodificadorWorker extends SwingWorker<Boolean, Boolean> {

        private DecoderConAES decAES;
        private javax.swing.JTextPane text;
        private javax.swing.JProgressBar jProgressBar1;
        private javax.swing.JLabel jLabel3;
        private boolean comprobarSuma;
        private String password;

        public DecodificadorWorker(DecoderConAES decAES, String password,
                javax.swing.JTextPane textPane, javax.swing.JProgressBar jProgressBar1,
                javax.swing.JLabel jLabel3, Boolean comprobarSuma) {
            this.decAES = decAES;
            this.text = textPane;
            this.password = password;
            this.jProgressBar1 = jProgressBar1;
            this.jLabel3 = jLabel3;
            this.comprobarSuma = comprobarSuma;
        }

        @Override
        protected Boolean doInBackground() throws Exception {
            try {
                publish(false);
                String mensaje = decAES.decode(password);

                if (comprobarSuma) {
                    boolean sumaVerificada = Utilities.compruebaHashMD5(mensaje, jTextField2.getText());
                    if (sumaVerificada) {
                        JOptionPane.showMessageDialog(null,
                                "El mensaje ha sido verificado," + '\n' + "su contenido es fiable",
                                "Comprobación de HASH",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "ATENCIÓN:" + '\n' + "El mensaje no ha podido ser verificado," + '\n' + "su contenido no es fiable",
                                "Comprobación de HASH",
                                JOptionPane.WARNING_MESSAGE);
                    }
                }
                this.text.setText(mensaje);
                publish(true);
                jLabel3.setText("Caracteres portados: " + mensaje.length());
                return true;
            } catch (Exception e1) {
                if(e1 instanceof CryptoException ){
                    e1.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                                "Contraseña errónea",
                                "Error!!",
                                JOptionPane.ERROR_MESSAGE);
                }
                publish(true);
                return false;
            }
        }

        @Override
        protected void process(List<Boolean> chunks) {
            jProgressBar1.setIndeterminate(!chunks.get(0));
        }
    }
}
